<template>
  <div class="shopbag">
    <van-nav-bar title="购物袋">
      <template #right>
        <div v-if="shopbagData.length > 0" @click="edit">
          {{ isEdit ? "完成" : "编辑" }}
        </div>
      </template>
    </van-nav-bar>

    <div class="shopbag-img"></div>
    <div>
      <div class="p-list-item" v-for="item in shopbagData" :key="item.sid">
        <!-- 组件 -->
        <ProList
          isSlide
          :proData="item"
          @simpleSelect="getSimpleSelectStatus"
          @remove="removeOne(item.sid, item.count)"
        >
          <van-stepper
            @change="changeCount(item)"
            v-model="item.count"
            theme="round"
            button-size="22"
            disable-input
          />
        </ProList>
      </div>
    </div>

    <!-- 提交订单栏 -->
    <div v-if="shopbagData.length > 0">
      <van-submit-bar
        v-show="!isEdit"
        :price="total"
        button-text="提交订单"
        button-color="#0c34ba"
        @submit="submitOrder"
      >
        <van-checkbox v-model="allCheck" @click="allSelect">全选</van-checkbox>
      </van-submit-bar>
      <van-submit-bar
        v-show="isEdit"
        button-text="删除选项"
        button-color="#0c34ba"
        @submit="removeSelect"
      >
        <van-checkbox v-model="allCheck" @click="allSelect">全选</van-checkbox>
      </van-submit-bar>
    </div>
    <div v-if="shopbagData.length === 0">
      <van-empty description="购物袋没有商品，赶紧逛一逛！" />
    </div>
  </div>
</template>

<script>
// 导入组件文件
import ProList from "../components/ProList.vue";
export default {
  name: "Shopbag",
  // 注册组件
  components: {
    ProList
  },
  data() {
    return {
      allCheck: false,
      isEdit: false,

      shopbagData: [],

      // 订单总价
      total: 0,
    };
  },
  created() {
    this.getShopbagData();
  },
  methods: {
    // 切换提交和删除按钮
    edit() {
      this.isEdit = !this.isEdit;
    },
    // 获取用户购物袋商品数据
    getShopbagData() {
      //获取token
      let tokenString = sessionStorage.getItem("token");

      //发起请求
      this.axios({
        method: "GET",
        url: "/findAllShopcart",
        params: {
          tokenString,
        },
      })
        .then((res) => {
          // console.log("数据333", res);
          if (res.data.code == 700) {
            //用户未登录, 拦截操作, 通知用户去登录
            this.$toast("请先登录");
            setTimeout(() => {
              this.$router.push({ name: "Login" });
            }, 2000);

            return;
          }
          if (res.data.code === 5000) {
            // 添加一个单选状态属性
            res.data.result.forEach((v) => {
              v.checked = false;
            });

            this.shopbagData = res.data.result;
          }
        })
        .catch((err) => {});
    },
    //全选
    allSelect() {
      this.shopbagData.forEach((v) => {
        v.checked = this.allCheck;
      });
    },
    //获取单选框的状态
    getSimpleSelectStatus() {
      this.sum();

      for (let i = 0; i < this.shopbagData.length; i++) {
        if (!this.shopbagData[i].checked) {
          this.allCheck = false;
          return;
        }
      }

      this.allCheck = true;
    },
    //计算订单总金额
    sum() {
      let total = 0;
      this.shopbagData.forEach((v) => {
        if (v.checked) {
          total += v.count * v.price;
        }
      });

      this.total = total * 100;
      // console.log("this.total",this.total);
    },
    //修改数量
    changeCount(item) {
      //获取token
      let tokenString = sessionStorage.getItem("token");
      this.axios({
        method: "POST",
        url: "/modifyShopcartCount",
        data: {
          tokenString,
          sid: item.sid,
          count: item.count,
        },
      })
        .then((res) => {
          // console.log(res);
          if (res.data.code == 700) {
            //用户未登录, 拦截操作, 通知用户去登录
            this.$toast("请先登录");
            setTimeout(() => {
              this.$router.push({ name: "Login" });
            }, 2000);

            return;
          }
          if (res.data.code === 6000) {
            this.sum();
            let count = 0;
            this.shopbagData.forEach((v) => {
              count += v.count;
            });
            this.$root.publicShopbagCount = count;
          }
          // 计算数量
          this.sum();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //删除勾选的商品
    removeSelect() {
      //获取勾选的商品
      let sids = [];
      let count = 0;
      this.shopbagData.forEach((v) => {
        if (v.checked) {
          sids.push(v.sid);
          count += v.count;
        }
      });
      if (sids.length === 0) {
        this.$toast("请选择删除的商品");
        return;
      }
      sids = JSON.stringify(sids);
      this.removeShopbagData(sids, count);
    },
    //删除商品(单个或者多个)
    removeShopbagData(sids, count) {
      let tokenString = sessionStorage.getItem("token");
      this.axios({
        method: "POST",
        url: "/deleteShopcart",
        data: {
          tokenString,
          sids,
        },
      })
        .then((res) => {
          // console.log(res);
          if (res.data.code == 700) {
            //用户未登录, 拦截操作, 通知用户去登录
            this.$toast("请先登录");
            setTimeout(() => {
              this.$router.push({ name: "Login" });
            }, 2000);

            return;
          }
          this.$toast(res.data.msg);
          if (res.data.code === 7000) {
            let sidsData = JSON.parse(sids);
            for (let i = 0; i < this.shopbagData.length; i++) {
              let sid = this.shopbagData[i].sid;
              if (sidsData.indexOf(sid) > -1) {
                this.shopbagData.splice(i, 1);
                i--;
              }
            }
            //重新判断是否全选
            this.getSimpleSelectStatus();

            //重新计算数量
            this.sum();

            this.$root.publicShopbagCount -= count;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //删除单个
    removeOne(sid, count) {
      let sids = JSON.stringify([sid]);
      this.removeShopbagData(sids, count);
    },
    //提交订单
    submitOrder() {
      //获取提交的商品
      let sids = [];
      this.shopbagData.forEach((v) => {
        if (v.checked) {
          sids.push(v.sid);
        }
      });
      if (sids.length === 0) {
        this.$toast("请选择商品");
        return;
      }
      this.$router.push({
        name: "ConfirmOrder",
        query: { sids: sids.join("-") },
      });
    },
  },
};
</script>

<style lang="less" scoped>
.shopbag {
  // padding-top: 46px;
  padding-bottom: 60px;
  /deep/.van-nav-bar__text {
    color: #0c34ba;
  }
}
.shopbag-img {
  height: 60px;
  background: url("../assets/imgs/shopbag_bg.png") no-repeat center center;
  background-size: cover;
}
.p-list-item {
  padding: 10px 10px 0;
  border-radius: 20px;
}
/deep/.van-submit-bar {
  bottom: 50px;
}
/deep/.van-submit-bar__button {
  margin-left: auto;
}
/deep/ .van-stepper--round .van-stepper__minus {
  color: #0c34ba;
  border-color: #0c34ba;
}
/deep/ .van-checkbox__icon--checked .van-icon {
  background-color: #0c34ba;
  border-color: #0c34ba;
}
/deep/.van-stepper__plus{
  background-color: #0c34ba;
  border-color: #0c34ba;
}
/deep/.van-submit-bar__price{
  color:#0c34ba ;
}
</style>